package com.yuncheng.common.utils;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import com.yuncheng.common.base.entity.CcBaseEntity;
import com.yuncheng.utils.I18nUtil;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.CurrentUserVo;

public class CcEntityUtil {

    public enum OpType {
        insert, update, saveOrUpdate
    }

    public static void setSysProperties(CcBaseEntity entity, OpType type,HttpServletRequest request) {
        Assert.notNull(entity, I18nUtil.message("parameter.error"));

        CurrentUserVo sysUser = ThreadContextHelper.getCurrentUser();
        String userName  = "";
        String orgCode = "";
        if(sysUser!=null){
             userName  = sysUser.getLoginName();
             orgCode = sysUser.getDeptCode();
        }
        String ip = "";
        if (null != request) {
        	String ipdata = IPUtils.getIpAddr(request);
        	if (StringUtils.isNotEmpty(ipdata)) {
                String[] ips = ipdata.split(",");
                if (ips.length > 0) {
                	ip = ips[0];
                }
        	}
        }
        switch (type) {
            case insert:
                entity.setCreateBy(userName);
                entity.setCreateTime(new Date());
                entity.setSysOrgCode(orgCode);
                entity.setUpdateBy(userName);
                entity.setUpdateTime(new Date());
//                entity.setCreateOrgCode(orgCode);
//                entity.setCreateByIp(ip);
//                entity.setDelFlag("0");
                break;
            case update:
                entity.setUpdateTime(new Date());
                entity.setUpdateBy(userName);
//                entity.setUpdateOrgCode(orgCode);
//                entity.setUpdateByIp(ip);
                break;
            case saveOrUpdate:
                entity.setCreateBy(userName);
                entity.setCreateTime(new Date());
                entity.setSysOrgCode(orgCode);
                entity.setUpdateTime(new Date());
                entity.setUpdateBy(userName);
//                entity.setUpdateOrgCode(orgCode);
//                entity.setUpdateByIp(ip);
//                entity.setDelFlag("0");
                break;
            default:
                break;
        }
    }
}
